package com.chainyoung.common.utils;

import android.text.TextUtils;

import com.chainyoung.common.bean.UserInfo;
import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.event.BaseEvent;
import com.google.gson.Gson;

import org.spongycastle.asn1.esf.SPuri;

public class CommonUtil {

    private static Gson gson = new Gson();

    /**
     * 获取用户信息，不为空表示已登录
     *
     * @return
     */
    public static UserInfo getUserInfo() {
        String str = SPUtil.getInstance().getString(LibConstant.USER_INFO, null);
        if (!StringUtil.isEmpty(str)) {
            UserInfo userInfo = gson.fromJson(str, UserInfo.class);
            return userInfo;
        }
        return null;
    }

    /**
     * 保存用户信息
     *
     * @param userInfo
     */
    public static void setUserInfo(UserInfo userInfo) {
        if (userInfo != null) {
            String json = gson.toJson(userInfo);
            SPUtil.getInstance().put(LibConstant.USER_INFO, json);
            if (!TextUtils.isEmpty(userInfo.getToken())) {
                SPUtil.getInstance().put(LibConstant.TOKEN, userInfo.getToken());
            }
        } else {
            SPUtil.getInstance().put(LibConstant.USER_INFO, StringUtil.EMPTY);
        }

    }


    /**
     * 登录成功以后的操作
     *
     * @param mEvent
     */
    public static void loginInSuccess(BaseEvent mEvent) {
        if (mEvent.getCode() == BaseEvent.EventCode.LOGIN_IN) {
            UserInfo mInfo = (UserInfo) mEvent.getData();
            SPUtil.getInstance().put(LibConstant.LOGIN_STATUS, true);
            SPUtil.getInstance().put(LibConstant.TOKEN, mInfo.getToken());
            SPUtil.getInstance().put(LibConstant.ACCOUNT, TextUtils.isEmpty(mInfo.getMobile()) ? mInfo.getEmail() : mInfo.getMobile());
            setUserInfo(mInfo);
        }
    }

    /**
     * 退出登录成功以后的操作
     */
    public static void signOutSuccess() {
        SPUtil.getInstance().put(LibConstant.LOGIN_STATUS, false);
        SPUtil.getInstance().put(LibConstant.TOKEN, StringUtil.EMPTY);
        SPUtil.getInstance().put(LibConstant.HISTORY_SEARCH, StringUtil.EMPTY);
        SPUtil.getInstance().removeKey(LibConstant.isShowAsset);
        SPUtil.getInstance().put(LibConstant.IS_PUT_JPUSH_ALIAS,false);
        setUserInfo(null);
    }


    /**
     * 获取登录状态
     * true表示已经登录
     * false表示未登录
     */
    public static boolean getLoginStatus() {
        Boolean mLoginStatus = SPUtil.getInstance().getBoolean(LibConstant.LOGIN_STATUS, false);
        if (mLoginStatus) {
            return true;
        } else {
            return false;
        }
    }

    private static long lastClickTime;

    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < 500) {
            return true;
        }
        lastClickTime = time;
        return false;
    }


}
